//
//  LoginViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/6.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "LoginViewController.h"

#import "RegisterViewController.h"
#import "PhoneViewController.h"
#import "PrefectPersonalInfoViewController.h"
#import "SelectInviterViewController.h"

#import "LoginTypeView.h"
#import "AccountView.h"
#import "ThirdLoginView.h"
#import "HButtonView.h"
#import "LoginGuideView.h"

#import "GetMessageCodeParam.h"

#import "TJNetWorking+Image.h"


@interface LoginViewController ()


/**
 logoImageView
 */
@property (nonatomic , strong) UIImageView *logoImageView;


/**
 loginTypeView
 */
@property (nonatomic , strong) LoginTypeView *loginTypeView;


/**
 AccountView
 */
@property (nonatomic , strong) AccountView *accountView;


/**
 loginBtn
 */
@property (nonatomic , strong) UIButton *loginBtn;


/**
 registerBtn
 */
@property (nonatomic , strong) UIButton *registerBtn;


/**
 forgetPassword
 */
@property (nonatomic , strong) UIButton *forgetPassword;


/**
 thirdLoginView
 */
@property (nonatomic , strong) ThirdLoginView *thirdLoginView;

/**
 三方登录uid
 */
@property (nonatomic , strong) NSString *uid;


@property (nonatomic, strong) LoginGuideView *guideView;


@end

@implementation LoginViewController


#pragma mark - view life cycle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = KWhiteColor;
    [self setUpView];
    
    if ([self isFirstLoad]) {
        [self.guideView show];
    }
}


#pragma mark - init method

- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}


- (void)initView {
    
    [self.view addSubview:self.logoImageView];
    [self.view addSubview:self.loginTypeView];
    [self.view addSubview:self.accountView];
    [self.view addSubview:self.loginBtn];
    [self.view addSubview:self.registerBtn];
    [self.view addSubview:self.forgetPassword];
    [self.view addSubview:self.thirdLoginView];
    
    @weakify(self);
    self.baseNavView.leftBlock = ^{
        @strongify(self);
        [self.accountView removeScreenView];
        [self.navigationController popViewControllerAnimated:YES];
    };
}


- (void) initLayout {
    
    [self.logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(TJ_NavBarHeight + 10);
    }];
    [self.loginTypeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.logoImageView.mas_bottom).offset(30);
        make.left.right.mas_equalTo(0);
    }];
    [self.accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.loginTypeView.mas_bottom);
        make.left.right.mas_equalTo(0);
    }];
    [self.loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.accountView.mas_bottom).offset(30);
        make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH - 60, 48));
        make.centerX.mas_equalTo(0);
    }];
    [self.registerBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.loginBtn.mas_left);
        make.top.mas_equalTo(self.loginBtn.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];
    [self.forgetPassword mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.loginBtn.mas_right);
        make.top.mas_equalTo(self.loginBtn.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(100, 30));
    }];
    [self.thirdLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.registerBtn.mas_bottom).offset(20);
        make.left.right.mas_equalTo(0);
    }];
}


- (void) initAction {
    
    RACSignal *sendVerifyStateSignal = [self.accountView.accountField.rac_textSignal map:^id _Nullable(NSString * _Nullable phoneNum) {
        return @([phoneNum isValidPhoneNumber]);
    }];
    
    RACSignal *countDowningSignal = RACObserve(self.accountView.verifyBtn, isCountDowning);
    RAC(self.accountView.verifyBtn,enabled) = [RACSignal combineLatest:@[sendVerifyStateSignal,countDowningSignal] reduce:^id _Nonnull(NSNumber *sendVerifyState, NSNumber *countDowningState){
        return @(sendVerifyState.boolValue && !countDowningState.boolValue);
    }];
    
    
    [self.loginTypeView.messageLogin addTarget:self action:@selector(messageLoginTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.loginTypeView.passwordLogin addTarget:self action:@selector(passwordLoginTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.accountView.verifyBtn addTarget:self action:@selector(verifyBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    
    [self.loginBtn addTarget:self action:@selector(loginBtnTapped) forControlEvents:UIControlEventTouchUpInside];

    [self.registerBtn addTarget:self action:@selector(registerBtnTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.forgetPassword addTarget:self action:@selector(forgetPasswordTapped) forControlEvents:UIControlEventTouchUpInside];

    
    @weakify(self);
    self.thirdLoginView.qqLoginBtn.tapped = ^{
        @strongify(self);
        [self getUserInfoForPlatform:UMSocialPlatformType_QQ];
    };
    self.thirdLoginView.wechatLoginBtn.tapped = ^{
        @strongify(self);
        [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
    };
    self.thirdLoginView.sinaLoginBtn.tapped = ^{
        @strongify(self);
        [self getUserInfoForPlatform:UMSocialPlatformType_Sina];
    };
    
}


- (void)initData {
    self.loginTypeView.messageLoginIsSelected = YES;
}


#pragma mark - delegate

#pragma mark - target action

//短信登陆
- (void)messageLoginTapped {
    
    if (!self.loginTypeView.messageLogin.selected) {
        self.loginTypeView.messageLoginIsSelected = YES;
        self.loginTypeView.passwordLoginIsSelected = NO;
        self.accountView.selectMessageLogin = YES;
    }
}

//密码登陆
- (void)passwordLoginTapped {
    
    if (!self.loginTypeView.passwordLogin.selected) {
        self.loginTypeView.passwordLoginIsSelected = YES;
        self.loginTypeView.messageLoginIsSelected = NO;
        self.accountView.selectPasswordLogin = YES;
    }
}


- (void)pulldownBtnTapped {
    if (self.accountView.pulldownBtn.selected) {
        self.accountView.pulldownBtn.selected = NO;
    } else {
        self.accountView.pulldownBtn.selected = YES;
//        CGFloat topSpacing = CGRectGetMaxY(self.loginTypeView.frame) + CGRectGetMaxY(self.accountView.accountBottomLine.frame) + TopBarHeight;
//        AccountDropView *accountDropView = [[AccountDropView alloc] initWithTopSpacing:topSpacing];
//        accountDropView.backgroundColor = KRedColor;
//        [accountDropView show];
//        [accountDropView setDismissViewBlock:^{
//            self.accountView.pulldownBtn.selected = NO;
//        }];
    }
}



//发送验证码
- (void)verifyBtnTapped {
    [self  getVerifyCodeRequest];
}

//登录接口
- (void)loginBtnTapped {
    
    //首次进页面，默认验证码登录
    LoginType loginType = LoginTypeCode;
   
    [self loginRequestWithType:loginType];
}

//注册
- (void)registerBtnTapped {
    RegisterViewController *registerViewController = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerViewController animated:YES];
}

//忘记密码
- (void)forgetPasswordTapped {
    PhoneViewController *phoneVC = [[PhoneViewController alloc] init];
    phoneVC.tipsTitle = ModifyPassword;
    [self.navigationController pushViewController:phoneVC animated:YES];
}


#pragma mark - private method
//获取验证码请求
- (void)getVerifyCodeRequest {
    NSString *phone = self.accountView.accountField.text;
    if (![phone isValidPhoneNumber]) {
        [self toastWithContent:@"请输入手机号"];
        return;
    };
    GetMessageCodeParam *param = [[GetMessageCodeParam alloc] init];
    param.phone = phone;
    param.type = GetMessageCodeTypeLogin;
    @weakify(self);
    [[[PigMarketApi sharedInstance] getMessageCodeWithParam:param] subscribeNext:^(GetMessageCode * _Nullable x) {
        
        @strongify(self);
        //倒计时
        [self.accountView.verifyBtn startCountDown];
        [self toastWithContent:@"验证码已发送手机，请注意查收"];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}


//登录接口请求
- (void)loginRequestWithType:(LoginType)loginType {
    
    NSNumber *loginTypeNum = @(LoginTypeCode);
    NSString *phone = @"";
    NSString *verityCode = @"";
    
    
    switch (loginType) {
        case LoginTypeCode://验证码和密码登录
        {
            verityCode = self.accountView.verifyField.text;
            phone = self.accountView.accountField.text;
            
            if (self.loginTypeView.passwordLoginIsSelected) {//密码登录
                loginTypeNum = @(LoginTypePassword);
            } else if(self.loginTypeView.messageLoginIsSelected){//验证码登录
                loginTypeNum = @(LoginTypeCode);
            }
            
            if (![phone isValidPhoneNumber]) {
                [self toastWithContent:@"请输入正确的手机号码"];
                return;
            }
            if ([verityCode isBlankString]) {
                [self toastWithContent:@"请输入验证码"];
                return;
            }
        }
            break;
            
        default://三方登录
        {
            if ([JTool iSNull:self.uid]) {
                [self toastWithContent:@"授权登录失败"];
                return;
            }
            phone = self.uid;
            loginTypeNum = @(loginType);
        }
            break;
    }

    
    @weakify(self);
    [[[PigMarketApi sharedInstance] userLoginWithAccount:phone msgCode:verityCode loginType:loginTypeNum] subscribeNext:^(UserInfo * _Nullable userInfo) {
        @strongify(self);
        
        switch ([userInfo.stage intValue]) {//登录请求后，判断不同的状态，跳转相应页面
            case StageTypeLoginSuccess://登录成功
            {
                [self.accountView removeScreenView];
                [self.navigationController popToRootViewControllerAnimated:YES];
                userInfo.isLogin = YES;
                [self saveUserAccountByPhone:phone];
                
                
                //IM登录
                [[ChatManager sharedInstance] loginIMWithUserName:userInfo.memberNum userSig:userInfo.userSig succ:^{
                    [self toastWithContent:@"聊天登录成功"];
                    userInfo.isIMLogin = YES;
                } fail:^(int code, NSString * _Nonnull msg) {
                    [self toastWithContent:msg];
                }];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationLoginStatusChanged object:self userInfo:@{@"loginstatus" : @(YES)}];
                
                //手机账号登录成功后 保存手机号码
                switch (loginType) {
                    case LoginTypeCode:
                    {
                        [[AccountDataProvider sharedInstance] saveAccount:phone];
                    }
                        break;
                        
                    default:
                        break;
                }
            }
                break;
            case StageTypePhone://填写手机号码
            {

                PhoneViewController *bindPhoneVC = [[PhoneViewController alloc] init];
                bindPhoneVC.tipsTitle = BindPhoneNumber;
                bindPhoneVC.uid = self.uid;
                bindPhoneVC.thirdLoginType = @(loginType);
                [self.navigationController pushViewController:bindPhoneVC animated:YES];
                break;
            }
            case StageTypeSelectInviter://选择邀请人
            {
                SelectInviterViewController *selectInviterVC = [[SelectInviterViewController alloc] init];
                [self.navigationController pushViewController:selectInviterVC animated:YES];
            }
                break;
            case StageTypePersonalInfomation://完善个人资料
            {

                PrefectPersonalInfoViewController *personalInfoVC = [[PrefectPersonalInfoViewController alloc] init];
                personalInfoVC.title = PrefectPersonalInfoTitle;
                [self.navigationController pushViewController:personalInfoVC animated:YES];
            }
                break;
            default:
                break;
        }
        
        //保存信息
        [UserInfoDataProvider sharedInstance].userInfo = userInfo;
        [TokenCacheManager sharedInstance].memberToken = userInfo.memberToken;
        
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
    
}

- (void)saveUserAccountByPhone:(NSString *)phone{
    
    if([phone isValidPhoneNumber]){
        
        NSMutableArray *mutableArrayCopy = [[kUserDefaults objectForKey:kUserAccountListKey] mutableCopy];
        
        if (!mutableArrayCopy) {
            mutableArrayCopy = [NSMutableArray array];
        }
        
        BOOL isbool = [mutableArrayCopy containsObject: phone];
        
        if (!isbool) {
            [mutableArrayCopy addObject:phone];
            [kUserDefaults setObject:mutableArrayCopy forKey:kUserAccountListKey];
            [kUserDefaults synchronize];
        }
    }
}


//三方登陆
- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:nil completion:^(id result, NSError *error) {
        UMSocialUserInfoResponse *resp = result;
        
        self.uid = resp.uid;//登录接口入参需要uid
        
        switch (platformType) {
            case UMSocialPlatformType_Sina:
                [self loginRequestWithType:LoginTypeSina];
                break;
            case UMSocialPlatformType_WechatSession:
                [self loginRequestWithType:LoginTypeWechat];
                break;
            case UMSocialPlatformType_QQ:
                [self loginRequestWithType:LoginTypeQQ];
                break;
            default:
                break;
        }
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        PMLog(@" uid: %@", resp.uid);
        PMLog(@" openid: %@", resp.openid);
        PMLog(@" accessToken: %@", resp.accessToken);
        PMLog(@" refreshToken: %@", resp.refreshToken);
        PMLog(@" expiration: %@", resp.expiration);
        // 用户数据
        PMLog(@" name: %@", resp.name);
        PMLog(@" iconurl: %@", resp.iconurl);
        PMLog(@" gender: %@", resp.unionGender);
        // 第三方平台SDK原始数据
        PMLog(@" originalResponse: %@", resp.originalResponse);
    }];
}


#pragma mark - getter and setter

- (UIImageView *)logoImageView {
    if (!_logoImageView) {
        _logoImageView = [[UIImageView alloc] init];
        _logoImageView.image = [UIImage imageNamed:@"login_logo"];
    }
    return _logoImageView;
}


//短信/密码
- (LoginTypeView *)loginTypeView {
    if (!_loginTypeView) {
        _loginTypeView = [[LoginTypeView alloc] init];
    }
    return _loginTypeView;
}


//
- (AccountView *)accountView {
    if (!_accountView) {
        _accountView = [[AccountView alloc] init];
        
        NSArray *phones = [kUserDefaults objectForKey:kUserAccountListKey];
        if (phones && phones.count >0) {
            _accountView.phones = phones;
        }
    }
    return _accountView;
}


- (UIButton *)loginBtn {
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setBackgroundImage:[UIImage imageNamed:@"login_loginbtn_default"] forState:UIControlStateNormal];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    }
    return _loginBtn;
}


- (UIButton *)registerBtn {
    if (!_registerBtn) {
        _registerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _registerBtn.adjustsImageWhenHighlighted = NO;
        [_registerBtn setTitle:@"注册账号" forState:UIControlStateNormal];
        [_registerBtn setTitleColor:[UIColor primaryColor] forState:UIControlStateNormal];
        _registerBtn.titleLabel.font = [UIFont middleFont];
    }
    return _registerBtn;
}


- (UIButton *)forgetPassword {
    if (!_forgetPassword) {
        _forgetPassword = [UIButton buttonWithType:UIButtonTypeCustom];
        _forgetPassword.adjustsImageWhenHighlighted = NO;
        [_forgetPassword setTitle:@"忘记密码？" forState:UIControlStateNormal];
        [_forgetPassword setTitleColor:UIColorFromRGB(0x7A7A7A) forState:UIControlStateNormal];
        _forgetPassword.titleLabel.font = [UIFont middleFont];
    }
    return _forgetPassword;
}


//QQ/微信/微博登陆
- (ThirdLoginView *)thirdLoginView {
    if (!_thirdLoginView) {
        _thirdLoginView = [[ThirdLoginView alloc] init];
    }
    return _thirdLoginView;
}


- (LoginGuideView *)guideView{
    
    if (!_guideView) {
        _guideView = [[LoginGuideView alloc] init];
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"新用户注册成功即可领取新人礼包10元（豚券）"attributes: @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:83/255.0 green:83/255.0 blue:83/255.0 alpha:1.0]}];
        
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:83/255.0 green:83/255.0 blue:83/255.0 alpha:1.000000]} range:NSMakeRange(0, 11)];
        
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:242/255.0 green:92/255.0 blue:98/255.0 alpha:1.000000]} range:NSMakeRange(11, 7)];
        
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:83/255.0 green:83/255.0 blue:83/255.0 alpha:1.000000]} range:NSMakeRange(18, 4)];
        
        _guideView.attributedStr = string;
    }
    return _guideView;
}


- (void)dealloc{
    
    [self.accountView removeScreenView];
}

@end
